﻿$(function () {
    $.extend({
        loading: function (text) {
            if (!text) {
                text = "处理中，请稍候...";
            }
            bootbox.dialog({ message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> ' + text + '</div>', closeButton: false });
        },

        submit: function (btn, timeout) {
            var form = $(btn).closest('form');

            form.validate();

            if (!timeout) {
                timeout = 2000;
            }
            if (form.valid()) {
                $.loading();
                setTimeout(function () { form.submit() }, timeout);
            }
        },
        pointTip: function () {
            $.get('/api/common/pointMessage', function (data) {
                layer.msg(data);
            });
        },
        alert: function (msg) {
            bootbox.alert({ title: '<i class="fa fa-info-circle"></i> 提示信息', message: msg, closeButton: false });
        }
    })
});

(function ($) {
    var o = $({});//自定义事件对象
    $.each({
        trigger: 'publish',
        on: 'subscribe',
        off: 'unsubscribe'
    }, function (key, val) {
        jQuery[val] = function () {
            o[key].apply(o, arguments);
        };
    });

    $(function () {
        $('.markdown-area').each(function (i, item) {
            var originalContent = marked($(item).find('input[type=hidden]').val());
            $(item).find('.markdown-body').html(originalContent);
        })
        $('.markdown-body pre code').each(function (i, block) {
            hljs.highlightBlock(block);
        });

        $('.markdown-body').find('a').attr('target', '_blank');

        setTimeout(signIn, 1000);
    })
})(jQuery);

$.ajaxSetup({
    beforeSend: function (xhr) {
        xhr.setRequestHeader("XSRF-TOKEN",
            $('input:hidden[name="__RequestVerificationToken"]').val());
    },
    statusCode: {
        401: function () {
            $.alert('对不起，您没有权限进行操作');
        },
        404: function () {
            location.href = '/NotFound';
        },
        500: function () {
            location.href = '/Error';
        }
    }
});

/**
 * 签到
 */
function signIn() {
    $.ajax({
        url: '/api/signin',
        type: 'post',
        success: function (data) {
            if (data) {
                $.pointTip();
            }
        },
        error: function (data) {
            bootbox.alert(data.responseText);
        }
    });
}

$.subscribe('sendsms', function (e, result) {
    console.info('send sms' + result)
    sendsms(result.account, result.btn, result.exist);
})
var mobilePattern =/^0?1[0-9]{10}$/
/**
 * 发送手机验证码，需要检测手机号是否存在
 * @param {object} btn 发送按钮对象
 * @param {object} mobileObj 要接收验证码的手机号对象
 * @param {boolean} existContinue 手机号存在，才继续发送验证码，否则弹出提示。默认 true

 */
function sendCode(btn, mobileObj,existContinue) {
    if (existContinue == undefined || existContinue == null) {
        existContinue = true;
    }

    var mobile = $(mobileObj).val();
    if (mobile == '') {
        bootbox.alert('请输入手机号');
        return false;
    }

    if (!mobilePattern.test(mobile)) {
        bootbox.alert('手机号码输入不正确');
        return false;
    }


    $.post('/api/account/check',
        { account: mobile },
        function (data) {
            if (existContinue) {
                if (data.exist) {
                    $.publish('sendsms', { account: mobile, btn: btn, exist: existContinue });
                } else {
                    bootbox.alert(data.type + '不存在');
                }
            } else {
                if (!data.exist) {
                    $.publish('sendsms', { account: mobile, btn: btn, exist: existContinue });
                } else {
                    bootbox.alert(data.type + '已经存在');
                }
            }
    })

}


function sendsms(account,btn,exist) {
    $.ajax({
        beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        url: '/api/sms',
        data: { account: account, needexist: exist },
        type: 'post',
        success: function (data) {
            bootbox.alert('验证码已发送')
            var originText = $(btn).html();
            $(btn).attr('disabled', true);
            let sec = 120;
            var intervalId = setInterval(function () {
                sec--;
                if (sec < 0) {
                    clearInterval(intervalId);
                    sec = 120;
                    $(btn).html(originText).attr('disabled', false);
                } else {
                    $(btn).html(sec + '秒后再次发送');
                }

            }, 1000);
        },
        error: function (data) {
            bootbox.alert('发送失败');
        }
    })
}

/**
 * 获取指定昵称的用户集合
 * @param {string} username 用户名
 */
function getUsersByUserName(username) {
}